package com.example.stringbufferlogger.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.stringbufferlogger.entity.FileCompareRecord;
import com.example.stringbufferlogger.entity.FileConfig;
import com.example.stringbufferlogger.entity.FileDataRecord;
import com.example.stringbufferlogger.entity.ReplayResult;
import com.example.stringbufferlogger.mapper.FileCompareRecordMapper;
import com.example.stringbufferlogger.mapper.FileDataRecordMapper;
import com.example.stringbufferlogger.mapper.InterfaceMappingConfigMapper;
import com.example.stringbufferlogger.mapper.ReplayResultMapper;
import com.example.stringbufferlogger.service.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

@Service
public class FileCompareRecordServiceImpl extends ServiceImpl<FileCompareRecordMapper, FileCompareRecord> implements FileCompareRecordService {
    @Autowired
    private FileDataRecordMapper fileDataRecordMapper;
    @Autowired
    private FileDataRecordService fileDataRecordService;
    @Autowired
    private FileConfigService fileConfigService;
    @Autowired
    private ReplayLogService replayLogService;

    @Autowired
    private ReplayResultMapper replayResultMapper;
    @Autowired
    private InterfaceMappingConfigMapper interfaceMappingConfigMapper;
    @Override
    public FileCompareRecord compareFiles(String requestId) {

        // 获取不匹配记录
        List<FileDataRecord> unmatchedRecords = fileDataRecordMapper.selectUnmatchedRecords(requestId);

        // 检查是否有可对比的记录
        QueryWrapper<FileDataRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("request_id", requestId).ne("is_compare", "1");
        Long totalRecords = fileDataRecordMapper.selectCount(queryWrapper);
        if (totalRecords == 0) {
            throw new IllegalArgumentException("当前请求暂无未比对文件");
        }

        // 更新不匹配记录
        fileDataRecordMapper.updateUnmatchedRecords(requestId);
        // 更新匹配记录
        fileDataRecordMapper.updateMatchedRecords(requestId);

        // 计算对比结果，若有不匹配记录则为 1，否则为 0
        String overallCompareResult = unmatchedRecords.isEmpty() ? "0" : "1";

//        // 创建整体对比记录
        FileCompareRecord overallRecord = new FileCompareRecord();
        if (!unmatchedRecords.isEmpty()) {
            overallRecord.setInterfaceUrl(unmatchedRecords.get(0).getInterfaceUrl());
        }
        overallRecord.setRequestId(requestId);
        overallRecord.setCompareResult(overallCompareResult);
        overallRecord.setCompareTime(new Timestamp(System.currentTimeMillis()));
        overallRecord.setCompareStatus("0");
        // 保存整体对比记录
//        //this.save(overallRecord);
//         return overallRecord;
      //根据 requestId 查询对应的 ReplayResult 记录
        ReplayResult replayResult = replayResultMapper.selectByRequestId(requestId);

        if (replayResult != null) {
            // 若记录存在，更新记录
            replayResult.setDiffFlag(overallCompareResult);
            replayResult.setReplayTime(LocalDateTime.now());
            replayResultMapper.updateByRequestId(replayResult);
        } else {
            // 若记录不存在，插入新记录
            replayResult = new ReplayResult();
            replayResult.setRequestId(requestId);
            replayResult.setDiffFlag(overallCompareResult);
            replayResult.setReplayTime(LocalDateTime.now());
            replayResultMapper.insert(replayResult);
        }
        return overallRecord;
    }
    @Override
    public List<FileCompareRecord> compareByReplayLogData() {
        List<FileCompareRecord> compareRecordsList = new ArrayList<>();
        List<Map<String, Object>> replayLogData = replayLogService.selectRequestIdAndPathByStatus();

        for (Map<String, Object> data : replayLogData) {
            String replayRequestId = (String) data.get("REQUESTID");
            try {
                    FileCompareRecord record = compareFiles( replayRequestId);
                    compareRecordsList.add(record);

            } catch (IllegalArgumentException e) {
                System.err.println("处理 requestId: " + replayRequestId + " 时出错: " + e.getMessage());
            }
        }
        return compareRecordsList;
    }

    @Override
    public List<FileCompareRecord> compareByInterfaceAndRequest(String interfaceUrl, String requestId) {
        List<FileCompareRecord> compareRecordsList = new ArrayList<>();
        List<FileConfig> fileConfigs = fileConfigService.getFileConfigsByInterfaceAdrs(interfaceUrl);
        if (fileConfigs.isEmpty()) {
            throw new IllegalArgumentException("未找到文件配置");
        }
        FileCompareRecord record = compareFiles(requestId);

        compareRecordsList.add(record);
        //}
        return compareRecordsList;
    }

    @Override
    public List<FileCompareRecord> compareByRequestId(String requestId) {
        String path = fileDataRecordService.getInterfaceUrlByRequestId(requestId);
        return compareByInterfaceAndRequest(path, requestId);
    }

    @Override
    public List<FileCompareRecord> compareByInterfaceUrl(String interfaceUrl) {
        String reqId = fileDataRecordService.getInterfaceUrlByRequestId(interfaceUrl);
        return compareByInterfaceAndRequest(interfaceUrl, reqId);
    }

    @Override
    public boolean saveBatch(Collection<FileCompareRecord> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<FileCompareRecord> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean updateBatchById(Collection<FileCompareRecord> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(FileCompareRecord entity) {
        return false;
    }

    @Override
    public FileCompareRecord getOne(Wrapper<FileCompareRecord> queryWrapper, boolean throwEx) {
        return null;
    }

    @Override
    public Map<String, Object> getMap(Wrapper<FileCompareRecord> queryWrapper) {
        return null;
    }

    @Override
    public <V> V getObj(Wrapper<FileCompareRecord> queryWrapper, Function<? super Object, V> mapper) {
        return null;
    }

}
